import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import mastermind.socket.protocol;
import mastermind.socket.socketConnect;

import mastermind.database.*;

/** Wrapper class to start server threads
 * 
 * @author Brendan
 *
 */
public class StartServer implements Runnable{
	
	private ServerSocket serverSocket;
    //private DataInputStream is;
	//private DataOutputStream os;
    private Thread thread = null;
    private ServerThread client = null;
    private TextDatabase database;

	/**
	 * Constructor, binds sockets and waits for a client.
	 */
	public StartServer()
	{
		try 
		{
			System.out.println("Server: Binding to port " + protocol.SERVER_PORT);
			serverSocket = new ServerSocket(protocol.SERVER_PORT);
			database = new TextDatabase(); // only one instance!!
			start();
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		}
	}
	
	/**
	 * (non-Javadoc)
	 * @see java.lang.Runnable#run()
	 */
	public void run()
	{
		while(thread != null)
		{
			try
			{
				System.out.println("Server: Waiting for a client...");
				addThread(serverSocket.accept());//new serverthread for each client
			}
			catch (IOException e)
			{
				System.out.println("Server: Error " + e);
			}
		}
	}
	
	/**
	 * Launches listener thread.
	 */
    public void start()
    {
    	if (thread == null)
    	{
    		thread = new Thread(this); 
    		thread.start();
    	}
    }
    
    public void stop()
    {
    	if (thread != null)
    	{  
    		thread.interrupt(); 
    		thread = null;
    	}
    }
    
    /** Accepts socket and creates a new thread to start processing
     * 
     * @param socket Socket to bind to.
     */
    public void addThread(Socket socket)
    {
    	System.out.println("Server: Client accepted " + socket);
        client = new ServerThread(this, socket,database);
        try
        {
        	client.open();
        	client.start();
        }
        catch(IOException e)
        {
        	System.out.println("Server: Error opening thread: " + e); 
        }
    }
	
    /*
    public socketConnect startServer()
    {
    	if(serverSocket == null)
    	{
    		serverSocket = new socketConnect();
    	}	
    	return serverSocket;
    }*/

}
